#实习三 

# 1.建立一个10个数的数值向量和一个因子（三组）
# 利用tapply函数计算不同组间的均值


# 练习1
# 利用sample函数随机生成10个数
num <- sample(1:100, 10, replace = TRUE)
# 创建三个组：math, eng, chi
group <- c("math", "math", "eng", "eng", "chi", "math","chi","eng","chi","chi")
# 手动将group转换为factor
group <- factor(group)
print("平均值：")
tapply(num, group, mean)
# 输出随机生成的num
print("原始数据：")
print(num)

# 练习2
# 建立2个10个数的数值向量，在与第一题中的数据合并成一个数据框
num2 <- sample(1:100, 10, replace = TRUE)
num3 <- sample(1:100, 10, replace = TRUE)
#使用data.frame()函数合并
df1 <- data.frame(num, num2, num3, group)
df1
#使用cbind()和rbind()函数合并
df2 <- cbind(num2, num3, num, group)
df3 <- rbind(num, num3, num2, group)
df2
df3




#练习3.1
# 读取多种数据格式文件，并对其进行合并
#1.使用merge()函数
library(openxlsx)
load_csv1 <- read.csv("ADdata2.csv")
load_csv1 <- data.frame(load_csv1)
load_txt1 <- read.table("ADdata1.txt", header = TRUE)
load_txt1 <- data.frame(load_txt1, header = TRUE)
load_txt2 <- read.table("ADdata4.txt",header = TRUE)
load_txt2 <- data.frame(load_txt2)
load_xlsx <- read.xlsx("ADdata3.xlsx")
load_xlsx <- data.frame(load_xlsx)
merge_data1 <- merge(load_csv1,load_xlsx,by.x = "X", by.y = "Var.1") #合并load_csv1,load_xlsx
merge_data2 <- merge(merge_data1,load_txt1,by.x = "X", by.y = "X") #再合并load_txt1
merge_data3 <- merge(merge_data2,load_txt2,by.x = "X", by.y = "X")#再合并load_txt2
#将合并的数据框导出成其他文件格式
library(xlsx)
write.csv(merge_data3, file = "merge_data1.csv")
write.table(merge_data3, file = "merge_data2.txt")
xlsx::write.xlsx(merge_data3, file = "merge_data3.xlsx")

#2.使用cbind()函数
#先使用order将数据框按公共列排序
tem1 <- load_txt1[order(load_txt1$X),]
tem2 <- load_txt2[order(load_txt2$X),]
tem3 <- load_csv1[order(load_csv1$X),]
tem4 <- load_xlsx[order(load_xlsx$Var.1),]
#使用cbind()合并排序好的数据框
cbind_merge_df1 <- cbind(tem1, tem2, tem3, tem4)
#将合并后的数据框中重复的列去除
cbind_merge_df1 <- cbind_merge_df1[c(-18, -35, -52)]







#练习3.2
#将csv文件读入合并整合成一个数据框
#获取该文件夹里面的所有csv文件名
list_name <- dir("./data",pattern = ".csv")
merge_data <- read.csv(file = paste("data",list_name[1],sep = "/",collapse = ","),header=T,sep=",")
#利用for循环读取文件并且将其合并
for (i in 2:length(list_name)){
  new_data <- read.csv(file = paste("data",list_name[i],sep = "/",collapse = ","),header=T,sep=",")
  merge_data <- cbind(merge_data,new_data)
}
#将合并的数据框写入一个新的excel文件
write.table(merge_data, file = "merge_data.xlsx")




#将tissue, cell type,和age的信息整合进入到同一个数据框中(不是很懂这一问，不知道如何操作)




